package com.hqyj.shop.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hqyj.shop.util.JwtUtil;
import com.hqyj.shop.util.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 项目:shop-admin-240701
 * 描述: Jwt 拦截验证
 * 时间:2024/10/9 11:34
 * 作者:admin
 * 版本:1.0
 **/
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1  验证是否携带token
        String token = request.getHeader("Authorization");
        if(StringUtils.isEmpty(token)){
            log.info("token不能为空");
            //设置响应编码
            response.setCharacterEncoding("utf-8");
            //获取响应对象
            PrintWriter pw = response.getWriter();
            //类型转换器
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(ResultVo.tokenError("token不能为空"));
            pw.print(json);
            //不允许访问
            return false;
        }
        //2 验证Token 是否合法
        String id = JwtUtil.getAudience(token);
        if(id==null){
            log.info("token验证不通过");
            //设置响应编码
            response.setCharacterEncoding("utf-8");
            //获取响应对象
            PrintWriter pw = response.getWriter();
            //类型转换器
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(ResultVo.tokenError("token验证不通过"));
            pw.print(json);
            //不允许访问
            return false;
        }
        //3 验证token 是否过期
        String salt = JwtUtil.getClaimByName(token,"jwtSalt").asString();
        DecodedJWT jwt = JwtUtil.verifyToken(token,salt);
        if(jwt==null){
            log.info("token过期");
            //设置响应编码
            response.setCharacterEncoding("utf-8");
            //获取响应对象
            PrintWriter pw = response.getWriter();
            //类型转换器
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(ResultVo.tokenError("token过期"));
            pw.print(json);
            //不允许访问
            return false;
        }
        log.info("token合法允许访问");
        //允许访问
        return true;
    }
}
